<template>
  <div>
    <header class="je-header">
      <div
        @tap="goBack($event)"
        class="back-btn mui-action-back"
      >
        <i class="jeicon jeicon-angle-left" />
      </div>
      <div class="title">
        {{ type === 'edit' ? '编辑日程' : '创建日程' }}
      </div>
      <div
        v-if="type === 'edit'"
        @tap="deleteCalendar"
        class="extra je-audio-btn"
      >
        删除
      </div>
      <div
        v-else
        class="extra"
      />
    </header>
    <div class="calendar_detail-wrp">
      <div class="calendar_detail">
        <div class="item">
          <div class="item_title">
            日程标题<span class="star">*</span>
          </div>
          <div class="item_content">
            <input
              ref="title"
              v-model="formdata.CALENDAR_TITLE"
              @focus="hideSoftKeybord"
              type="text"
              maxlength="50"
              placeholder="请输入标题..."
            >
          </div>
        </div>
        <div class="item">
          <div class="item_title">
            创建人
          </div>
          <div class="item_content">
            {{ formdata.SY_CREATEUSERNAME }}
          </div>
        </div>
        <div class="item">
          <div class="item_title">
            全天
          </div>
          <div
            @tap="handleAllday"
            class="item_content arrow je-audio-btn"
          >
            {{ formdata.CALENDAR_YESORNO_NAME }}
          </div>
        </div>
        <div class="item">
          <div class="item_title">
            类型
          </div>
          <div
            @tap="handleSelectClick()"
            class="item_content arrow je-audio-btn"
          >
            {{ formdata.CALENDAR_CALENDARTYPE_NAME }}
          </div>
        </div>
        <div class="item">
          <div class="item_title">
            开始时间<span class="star">*</span>
          </div>
          <div
            @tap="handleDateClick('CALENDAR_STARTTIME')"
            class="item_content arrow je-audio-btn"
          >
            {{ formdata.CALENDAR_STARTTIME || '请选择开始时间' }}
          </div>
        </div>
        <div class="item">
          <div class="item_title">
            结束时间<span class="star">*</span>
          </div>
          <div
            @tap="handleDateClick('CALENDAR_ENDTIME')"
            class="item_content arrow je-audio-btn"
          >
            {{ formdata.CALENDAR_ENDTIME || '请选择结束时间' }}
          </div>
        </div>
        <div class="item">
          <div class="item_title">
            提醒
          </div>
          <div
            class="item_content"
            style="display: flex; justify-content: flex-end"
          >
            <je-switch
              :change="switchSelect"
              :checked="reminder"
              class="scl"
            />
          </div>
        </div>
        <div class="item">
          <div class="item_title">
            颜色
          </div>
          <div
            @tap="handleColorlick()"
            class="item_content arrow je-audio-btn"
          >
            {{ getColorLabel }}
          </div>
        </div>
        <div class="item">
          <div class="item_title">
            内容<span class="star">*</span>
          </div>
          <div class="item_content">
            <!-- <editor
              ref="editor"
              :content.sync="formdata.CALENDAR_NOTES"
              @change="editorChange"
            /> -->
            <quill-editor
              ref="myQuillEditor"
              v-model="CALENDAR_NOTES"
              :options="opts"
              @focus="scroll2bottom($event)"
            />
          </div>
        </div>
      </div>
      <float-btn
        @tap="save"
        type="icon"
        text="jeicon-save"
      />
    </div>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor';
import floatBtn from '@/components/floatbtn';
import JeSwitch from '@/components/switch';
import options from './editorOptions';
// import VueHtml5Editor from '../../utils/vue-html5-editor';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

// const editor = new VueHtml5Editor(options);
export default {
  name: 'CalendarDetail',
  components: { floatBtn, JeSwitch, quillEditor },
  data() {
    return {
      opts: options,
      dtPicker: null,
      picker: null,
      startTime: '起始时间',
      endTime: '结束时间',
      selectList: [
        {
          value: '1',
          text: '日常记录',
        },
        {
          value: '2',
          text: '本周工作',
        },
        {
          value: '3',
          text: '下周计划',
        },
      ],
      alldayList: [
        {
          value: '1',
          text: '是',
        },
        {
          value: '0',
          text: '否',
        },
      ],
      alldayPicker: null,
      formdata: {
        tableCode: 'JE_SYS_CALENDAR',
      },
      CALENDAR_NOTES: '',
      colorList: [
        {
          value: '#FF625C',
          text: '红色',
        },
        {
          value: '#F9A646',
          text: '橙色',
        },
        {
          value: '#F4CE4A',
          text: '黄色',
        },
        {
          value: '#386BD0',
          text: '蓝色',
        },
        {
          value: '#6DCC51',
          text: '绿色',
        },
        {
          value: '#4BB8F3',
          text: '浅蓝',
        },
        {
          value: '#D088E1',
          text: '紫色',
        },
      ],
      // showPlaceholder: false,
      reminder: true,
      type: '',
      content: '',
      initFormdata: {},
      upDate: '',
    };
  },
  computed: {
    getColorLabel() {
      const label = this.colorList.filter(n => n.value == this.formdata.CALENDAR_COLOR);
      return (label && label[0])?label[0].text:"标题";
    },
  },
  created() {
    const { item, type, upDate } = this.$route.query;
    this.upDate = upDate || '';
    // 类型
    this.picker = new mui.PopPicker();
    this.picker.setData(this.selectList);
    // 颜色
    this.colorPicker = new mui.PopPicker();
    this.colorPicker.setData(this.colorList);
    // 是否全天
    this.alldayPicker = new mui.PopPicker();
    this.alldayPicker.setData(this.alldayList);
    this.type = type;
    if (type === 'edit') {
      this.formdata.JE_SYS_CALENDAR_ID = item.JE_SYS_CALENDAR_ID;
    }
    this.formdata.SY_CREATEUSER = item.SY_CREATEUSER;
    this.formdata.SY_CREATEUSERNAME = item.SY_CREATEUSERNAME;
    this.formdata.SY_CREATEUSERID = item.SY_CREATEUSERID;
    this.formdata.CALENDAR_TITLE = item.CALENDAR_TITLE || '';
    this.$set(this.formdata, 'CALENDAR_NOTES', JE.htmlDecode(item.CALENDAR_NOTES) || '');
    this.$set(this, 'CALENDAR_NOTES', JE.htmlDecode(item.CALENDAR_NOTES) || '');
    this.$set(this.formdata, 'CALENDAR_COLOR', item.CALENDAR_COLOR || '#386BD0');
    this.colorPicker.pickers[0].setSelectedValue(item.CALENDAR_COLOR || '#386BD0');
    this.formdata.CALENDAR_GROUPCOLOR = '';
    // 全天
    this.$set(this.formdata, 'CALENDAR_YESORNO_CODE', item.CALENDAR_YESORNO_CODE || this.alldayList[0].value);
    this.$set(this.formdata, 'CALENDAR_YESORNO_NAME', item.CALENDAR_YESORNO_NAME || this.alldayList[0].text);
    this.alldayPicker.pickers[0].setSelectedValue(item.CALENDAR_YESORNO_CODE || this.alldayList[0].value);

    if (item.CALENDAR_YESORNO_CODE && item.CALENDAR_YESORNO_CODE == '0') {
      this.dtPicker = new mui.DtPicker({
        type: 'datetime',
      });
      this.$set(this.formdata, 'CALENDAR_STARTTIME', item.CALENDAR_STARTTIME.substring(0, item.CALENDAR_STARTTIME.length - 3) || '');
      this.$set(this.formdata, 'CALENDAR_ENDTIME', item.CALENDAR_ENDTIME.substring(0, item.CALENDAR_ENDTIME.length - 3) || '');
    } else {
      this.dtPicker = new mui.DtPicker({
        type: 'date',
      });
      this.$set(this.formdata, 'CALENDAR_STARTTIME', item.CALENDAR_STARTTIME.split(' ')[0] || '');
      this.$set(this.formdata, 'CALENDAR_ENDTIME', (item.CALENDAR_ENDTIME && item.CALENDAR_ENDTIME.split(' ')[0]) || '');
    }
    // 类型
    this.$set(this.formdata, 'CALENDAR_CALENDARTYPE_CODE', item.CALENDAR_CALENDARTYPE_CODE || this.selectList[0].value);
    this.$set(this.formdata, 'CALENDAR_CALENDARTYPE_NAME', item.CALENDAR_CALENDARTYPE_NAME || this.selectList[0].text);
    this.picker.pickers[0].setSelectedValue(item.CALENDAR_CALENDARTYPE_CODE || this.selectList[0].value);
    // 提醒
    if (item && item.CALENDAR_REMINDER_CODE) {
      if (item.CALENDAR_REMINDER_CODE === '1') {
        this.$set(this, 'reminder', true);
      } else {
        this.$set(this, 'reminder', false);
      }
    }
    // this.$set(this, 'reminder', item.CALENDAR_REMINDER_CODE === '1' || true);
    this.$set(this.formdata, 'CALENDAR_REMINDER_CODE', this.reminder ? '1' : '0');
    this.$set(this.formdata, 'CALENDAR_REMINDER_NAME', this.reminder ? '是' : '否');
    this.$set(this.formdata, 'CALENDAR_MESSAGETYPE_CODE', this.reminder ? 'DWR' : '');
    this.$set(this.formdata, 'CALENDAR_MESSAGETYPE_NAME', this.reminder ? '页面' : '');
    // 新增日程id为空
    this.formdata.JE_SYS_CALENDAR_ID = type === 'edit' ? item.JE_SYS_CALENDAR_ID : '';
    this.initFormdata = JSON.parse(JSON.stringify(this.formdata));
  },
  mounted() {
    // 去掉富文本内置padding & 上边框
    // document.getElementsByClassName('content')[0].style.padding = '0';
    // document.getElementsByClassName('content')[0].style.minHeight = '50px';
    // document.getElementsByClassName('toolbar')[0].style.display = 'none';
  },
  methods: {
    blurInput() {
      this.$refs.title.blur();
      // this.$refs.editor.blur();
    },
    // 全天选择
    handleAllday() {
      this.blurInput();
      this.alldayPicker.show((items) => {
        this.formdata.CALENDAR_YESORNO_CODE = items[0].value;
        this.formdata.CALENDAR_YESORNO_NAME = items[0].text;
        if (items[0].value == '0') {
          this.dtPicker = new mui.DtPicker({
            type: 'datetime',
          });
        } else {
          this.dtPicker = new mui.DtPicker({
            type: 'date',
          });
        }
      });
    },
    handleSelectClick() {
      this.blurInput();
      this.picker.show((items) => {
        this.formdata.CALENDAR_CALENDARTYPE_CODE = items[0].value;
        this.formdata.CALENDAR_CALENDARTYPE_NAME = items[0].text;
      });
    },
    handleColorlick() {
      this.blurInput();
      this.colorPicker.show((items) => {
        this.formdata.CALENDAR_COLOR = items[0].value;
      });
    },
    goBack(event) {
      event.stopPropagation();
      if (this.hasChange()) {
        const btnArray = ['取消', '确定'];
        mui.confirm('是否放弃编辑?', '', btnArray, (e) => {
          if (e.index === 1) {
            return mui.back();
          }
        });
      } else {
        mui.back();
      }
    },
    deleteCalendar() {
      const btnArray = ['取消', '删除'];
      mui.confirm('确定删除吗?', '', btnArray, (e) => {
        if (e.index === 1) {
          JE.ajax({
            url: '/je/calendar/calendar/doRemove',
            params: {
              tableCode: 'JE_SYS_CALENDAR',
              ids: this.formdata.JE_SYS_CALENDAR_ID,
            },
          }).then((data) => {
            if (data && data.success) {
              JE.msg('删除成功');
              const parent = plus.webview.currentWebview().opener();
              mui.fire(parent, 'research', { upDate: this.upDate });
              mui.back();
            } else {
              JE.msg('删除失败，未知错误');
            }
          }).catch(() => {
            JE.msg('删除失败');
          });
        }
      });
    },
    hasChange() {
      for (const key in this.formdata) {
        if (this.formdata[key] != this.initFormdata[key]) {
          return true;
        }
      }
      return false;
    },
    handleDateClick(target) {
      this.blurInput();
      if (target === 'CALENDAR_STARTTIME') {
        this.dtPicker.setSelectedValue(this.formdata.CALENDAR_STARTTIME);
      } else {
        this.dtPicker.setSelectedValue(this.formdata.CALENDAR_ENDTIME);
      }
      this.dtPicker.show(({ value }) => {
        if (target === 'CALENDAR_STARTTIME' && this.formdata.CALENDAR_ENDTIME && this.formdata.CALENDAR_ENDTIME < value) {
          return JE.msg('开始时间不能晚于结束时间!');
        }
        if (target === 'CALENDAR_ENDTIME' && this.formdata.CALENDAR_STARTTIME && this.formdata.CALENDAR_STARTTIME > value) {
          return JE.msg('结束时间不能早于开始时间!');
        }
        this.formdata[target] = value;
      });
    },
    save() {
      if (!this.formdata.CALENDAR_TITLE) {
        JE.msg('标题不能为空');
        return;
      }
      if (!/^(?!(\s+$))/.test(this.formdata.CALENDAR_TITLE)) {
        JE.msg('请输入正确的标题内容');
        return;
      }
      if (!this.formdata.CALENDAR_TITLE.length > 50) {
        JE.msg('标题不能超过50个字');
        return;
      }
      if (!this.formdata.CALENDAR_STARTTIME) {
        JE.msg('开始时间不能为空');
        return;
      }
      if (!this.formdata.CALENDAR_ENDTIME) {
        JE.msg('结束时间不能为空');
        return;
      }
      if (!this.CALENDAR_NOTES) {
        JE.msg('内容不能为空');
        return;
      }
      if (!this.utilEditor(this.CALENDAR_NOTES) || !/^(?!(\s+$))/.test(this.utilEditor(this.CALENDAR_NOTES))) {
        JE.msg('请输入正确的内容');
        return;
      }
      if (this.utilEditor(this.CALENDAR_NOTES).length > 2000) {
        JE.msg('内容不能超过2000个字');
        return;
      }
      // 处理时间  后台需要的是年月日时分秒
      if (this.formdata.CALENDAR_YESORNO_CODE == '0') {
        this.formdata.CALENDAR_STARTTIME = `${this.formdata.CALENDAR_STARTTIME}:00`;
        this.formdata.CALENDAR_ENDTIME = `${this.formdata.CALENDAR_ENDTIME}:00`;
      } else {
        this.formdata.CALENDAR_STARTTIME = `${this.formdata.CALENDAR_STARTTIME} 00:00:00`;
        this.formdata.CALENDAR_ENDTIME = `${this.formdata.CALENDAR_ENDTIME} 00:00:00`;
      }
      this.formdata.CALENDAR_NOTES = JE.htmlEncode(this.CALENDAR_NOTES);
      let url = '';
      if (this.type === 'add') {
        url = '/je/calendar/calendar/doSave';
      } else {
        url = '/je/calendar/calendar/doUpdate';
      }
      //const waiting = plus.nativeUI.showWaiting('保存中');
      JE.ajax({
        url,
        params: this.formdata,
      }).then((data) => {
        if (data && data.success) {
          JE.msg('保存成功');
          // const parent = plus.webview.currentWebview().opener();
          // mui.fire(parent, 'research', { upDate: this.upDate });
          mui.back();
          // this.$router.push({
          //     path: '/JE-PLUGIN-CALENDAR',
          //     query: {
          //       type: 'refreshList',
          //     },
          //   });
        } else {
          JE.msg('保存失败，未知错误');
        }
       // waiting.close();
      }).catch(() => {
        //waiting.close();
      });
    },
    utilEditor(str) {
      let utilStr = str;
      const reg = /<\/?.+?\/?>/g;
      utilStr = utilStr.replaceAll(reg, '');
      utilStr = utilStr.replaceAll('&nbsp;', '');
      return utilStr;
    },
    switchSelect() {
      this.reminder = !this.reminder;
      this.formdata.CALENDAR_REMINDER_CODE = this.reminder ? '1' : '0';
      this.formdata.CALENDAR_REMINDER_NAME = this.reminder ? '是' : '否';
      this.formdata.CALENDAR_MESSAGETYPE_CODE = this.reminder ? 'DWR' : '';
      this.formdata.CALENDAR_MESSAGETYPE_NAME = this.reminder ? '页面' : '';
    },
    hideSoftKeybord() {
      if (mui.os.android) {
        plus.key.hideSoftKeybord();
      }
    },
    scroll2bottom() {
      setTimeout(() => {
        // getBoundingClientRect()
        document.getElementsByClassName('calendar_detail')[0].style.overflow = 'hidden';
        document.getElementsByClassName('calendar_detail')[0].scrollTop = document.getElementsByClassName('calendar_detail')[0].scrollHeight;
        document.getElementsByClassName('calendar_detail')[0].style.overflow = 'scroll';
      }, 500);
    },
  },
};
</script>

<style lang="less" scoped>
  @import '~@/theme/index.less';
  .calendar_detail-wrp {
    position: absolute;
    top: unit(45 * @hd, px);
    right: 0;
    bottom: 0;
    left: 0;
    // background: #F8F8F8;
    .calendar_detail {
      position: absolute;
      top: 0;
      right: @h-spacing-sm;
      bottom: 0;
      left: @h-spacing-sm;
      background: #ffffff;
      padding: 0 10 * @hd;
      overflow: scroll;
      .item {
        display: flex;
        // align-items: center;
        justify-content: center;
        padding: 11 * @hd 0;
        width: 100%;
        &:not(:last-child) {
          border-bottom: 1px solid rgba(245,245,245,1);
        }
        .item_title {
          color: #A9ABA9;
          width: 70 * @hd;
          font-size: 15 * @hd;
          text-align: left;
          flex-shrink: 0;
          .star {
            color: #FF8E73;
          }
        }
        .item_content {
          flex: 1;
          color: @color-text-base;
          margin-left: 15 * @hd;
          position: relative;
          height: 20 * @hd;
          font-size: 16* @hd;
          &.arrow {
            padding-right: 20 * @hd;
            &:after {
              content: '';
              border: 1px solid #ADAFAD;
              border-top-color: transparent;
              border-left-color: transparent;
              width: 8px;
              height: 8px;
              position: absolute;
              right: 3px;
              top: 0;
              transform: rotate(45deg);
            }
          }
          > input {
            border: 0;
            margin: 0;
            padding: 0;
            font-size: 16 * @hd;
            height: auto;
          }
          .vue-html5-editor {
            border: 0;
            font-size: 16 * @hd;
            word-break: break-all;
          }
          .placeholder {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 500px;
          }
          .scl {
            transform: scale(0.6);
          }
        }
      }
    }
  }
</style>

<style lang="less">
@import "~@/theme/index.less";

header.je-header {
  height: unit(45 * @hd, px);
  // box-sizing: content-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #ffffff;
  background-color: #536dfe;
  padding: 0 30px;
  font-size: 32px;
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 1000;
  .back-btn {
    .back-text {
      margin-left: 5px;
    }
    i {
      color: #ffffff;
      font-size: 32px;
    }
  }
  .title {
    text-align: center;
  }
  .extra {
    text-align: right;
  }
  //  mainTitle 模式下 中间区域最大自适应，左右两边补充
  &:not(.main-title) > * {
    flex: 1;
  }
  .title {
    flex: 1;
  }
  &.hide-btn {
    padding-left: 15px;
    padding-right: 18px;
  }
  &.main-title {
  }
}
.je-content {
  padding-top: unit(45 * @hd, px);
}
</style>
<style lang="less">;
// [contenteditable] {
//   -webkit-user-select: text;
//   user-select: text;
// }
.mui-backdrop {
  position: absolute;
}
.calendar_detail::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
}
</style>
<style lang="less">
@import "~@/theme/index.less";
  .calendar_detail-wrp {
    .quill-editor * {
      -webkit-user-select: text;
      user-select: text;
      font-size: 16* @hd;
      color: rgb(63, 63, 63);
    }
    .ql-toolbar {
      display: none;
    }
    .ql-container {
      border: 0;
      > div[contenteditable="true"] {
        min-height: 100 * @hd;
      }
    }
    .ql-editor {
      padding: 0;
    }
  }
</style>
